<template>
    <div class="user-contain">
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }"
                >首页</el-breadcrumb-item
            >
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 搜索添加区域 -->
        <el-card class="box-card">
            <el-row :gutter="60">
                <el-col :span="7">
                    <div class="grid-content bg-purple">
                        <el-input
                            placeholder="请输入内容"
                            class="input-with-select"
                            v-model="querryinfo.query"
                            clearable
                            @clear="getUserList"
                        >
                            <el-button
                                slot="append"
                                icon="el-icon-search"
                                @click="getUserList"
                            ></el-button>
                        </el-input>
                    </div>
                </el-col>
                <el-col :span="3">
                    <div class="grid-content bg-purple">
                        <el-button
                            type="primary"
                            icon="el-icon-search"
                            @click="dialogVisible = true"
                            >添加用户</el-button
                        >
                    </div>
                </el-col>
            </el-row>
        </el-card>
        <!-- 表格区域 -->
        <el-table :data="userList" style="width: 100%" border stripe>
            <!-- type="index" 就是索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="username" label="姓名" width="180">
            </el-table-column>
            <el-table-column prop="mobile" label="电话" width="180">
            </el-table-column>
            <el-table-column prop="email" label="邮箱"> </el-table-column>
            <el-table-column prop="role_name" label="角色"></el-table-column>
            <el-table-column prop="mg_state" label="状态">
                <template slot-scope="scope">
                    <!-- {{ scope.row }} 可以获取当前行的数据 -->
                    <el-switch
                        v-model="scope.row.mg_state"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        @change="changeStatus(scope.row)"
                    >
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                    <!-- 外层是文字提示 -->
                    <el-tooltip
                        class="item"
                        effect="dark"
                        content="修改"
                        placement="top"
                        :enterable="false"
                    >
                        <!-- 修改按钮 -->
                        <el-button
                            type="primary"
                            icon="el-icon-edit"
                            size="mini"
                            @click="editdata(scope.row.id)"
                        ></el-button>
                    </el-tooltip>

                    <!-- 删除按钮 -->
                    <el-tooltip
                        class="item"
                        effect="dark"
                        content="删除"
                        placement="top"
                        :enterable="false"
                    >
                        <el-button
                            type="primary"
                            icon="el-icon-delete"
                            size="mini"
                            @click="deletedata(scope.row.id)"
                        ></el-button>
                    </el-tooltip>

                    <!-- 分配角色按钮 -->
                    <el-tooltip
                        class="item"
                        effect="dark"
                        content="分配角色"
                        placement="top"
                        :enterable="false"
                    >
                        <el-button
                            type="primary"
                            icon="el-icon-setting"
                            size="mini"
                            @click="setUsers(scope.row)"
                        ></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <!-- 页码区域 -->
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="querryinfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="querryinfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        >
        </el-pagination>
        <!-- 对话框区域 -->
        <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="40%"
            @close="clearitem()"
        >
            <!-- 主体区域 -->
            <el-form
                :model="userForm"
                :rules="itemrules"
                ref="ruleFormRef"
                label-width="100px"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username"> </el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="userForm.password"> </el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="userForm.email"> </el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="userForm.mobile"> </el-input>
                </el-form-item>
            </el-form>
            <!-- 尾部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="adduser()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户数据 对话框 -->
        <el-dialog
            title="修改用户数据"
            :visible.sync="editDialogVisible"
            width="40%"
            @close="resetEditForm()"
        >
            <el-form
                :model="editForm"
                :rules="editFormRules"
                ref="editFormRef"
                label-width="100px"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="subEditData()"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
        <!-- 分配角色 对话框 -->
        <el-dialog
            title="分配角色"
            :visible.sync="setUserDialogVisible"
            width="40%"
            @close="setRoleDialogClose"
        >
            <p>当前用户：{{ userinfo.username }}</p>
            <p>当前角色：{{ userinfo.role_name }}</p>
            <p>
                分配新角色：
                <el-select v-model="roleSelectId" placeholder="请选择">
                    <el-option
                        v-for="item in rolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setUserDialogVisible = false"
                    >取 消</el-button
                >
                <el-button type="primary" @click="editRoleList()"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
  data: function () {
    // 定义邮箱校验规则
    const checkEmail = (rule, val, callback) => {
      const regEmail = /^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+.[a-zA-Z]{2,3}$/
      if (regEmail.test(val)) {
        // 合法的邮箱
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    const checkMobile = (rule, val, callback) => {
      const regMobile = /^1[23456789]\d{9}$/
      if (regMobile.test(val)) {
        return callback()
      }
      callback(new Error('请输入合法的手机号'))
    }
    return {
      // 角色列表数据
      userinfo: {},
      // 分配角色对话框是否打开
      setUserDialogVisible: false,
      // 角色列表数据
      rolesList: [],
      // 下拉选择框中双向绑定值
      roleSelectId: '',
      // 请求体
      querryinfo: {
        // 搜索关键字
        query: '',
        // 当前页码数
        pagenum: 1,
        // 每页展示多少条
        pagesize: 2
      },
      // 用户列表数据
      userList: [],
      //   总条数
      total: 0,
      //   是否打开对话框
      dialogVisible: false,
      //   添加用户表单的数据
      userForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //   校验规则
      itemrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //   是否打开编辑用户对话框
      editDialogVisible: false,
      //   编辑数据表单
      editForm: {},
      //   编辑数据表单的校验规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    getUserList: async function () {
      const { data: res } = await this.$http.get('users', { params: this.querryinfo })
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      //   console.log(this.userList)
      this.total = res.data.total
    },
    handleSizeChange: function (sizeChange) {
      //   console.log(sizeChange)
      this.querryinfo.pagesize = sizeChange
      this.getUserList()
    },
    handleCurrentChange: function (currentPage) {
      //   console.log(currentPage)
      this.querryinfo.pagenum = currentPage
      this.getUserList()
    },
    changeStatus: async function (userinfo) {
      //   console.log(userinfo)
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      //   console.log(res)
      // 如果没有修改成功就要把 状态改回原样
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('修改用户状态失败')
      } else {
        return this.$message.success('修改用户状态成功')
      }
    },
    // 监听用户关闭对话框,之后会调用清空表单操作
    clearitem: function () {
      this.$refs.ruleFormRef.resetFields()
    },
    // 点击对话框的确定,添加用户
    adduser: function () {
      // 表单预校验
      this.$refs.ruleFormRef.validate(async (boolean) => {
        if (!boolean) return false
        const { data: res } = await this.$http.post('users', this.userForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 关闭对话框
        this.dialogVisible = false
        // 重新渲染数据
        this.getUserList()
      })
    },
    // 修改用户数据
    editdata: async function (id) {
      //   console.log(id)
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.editForm = res.data
    },
    // 清空表单 清空之前输入的数据
    resetEditForm: function () {
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改后的用户数据
    subEditData: function () {
      this.$refs.editFormRef.validate(async boolean => {
        if (!boolean) return false
        // 表单预校验通过后 提交修改后的数据
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if (res.meta.status !== 200) return this.$message.error('修改用户信息失败')
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据
        this.getUserList()
        this.$message.success('修改用户信息成功')
      })
    },
    // 删除用户数据
    deletedata: async function (id) {
      console.log(id)
      // 弹框提示
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // confirmResult 点击确定的话得到的是 confirm 字符串
      // confirmResult 点击取消会得到 一个错误的消息 用 catch 捕获的话 得到字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getUserList()
    },
    setUsers: async function (userinfo) {
      // console.log(userinfo)
      this.userinfo = userinfo
      // 打开对话框前先获取数据
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$http.error('获取角色列表失败')
      this.rolesList = res.data
      this.setUserDialogVisible = true
    },
    // 分配角色
    editRoleList: async function () {
      if (!this.roleSelectId) return this.$message.error('请重新分配角色')
      const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`, { rid: this.roleSelectId })
      if (res.meta.status !== 200) return this.$message.error('重新分配角色失败')
      this.$message.success('分配角色成功')
      this.getUserList()
      this.setUserDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClose: function () {
      this.rolesList = {}
      this.roleSelectId = ''
    }
  },
  created: function () {
    this.getUserList()
  }
}
</script>
<style lang="less" scoped>
.user-contain {
    width: 80%;
    height: auto;

    .el-card {
        background-color: #ffffff;
        box-shadow: 0 1px 1px rgb(0, 0, 0.3);

        .el-input {
            background-color: #ffffff !important;
            border: solid 1px #fff;
            border-radius: 4px;
        }
    }
    .el-breadcrumb {
        font-size: 20px;
        margin-bottom: 15px;
    }
    .el-table {
        margin-top: 1px;
        font-size: 14px;
    }
    .el-pagination {
        background-color: #ffffff;
        margin-top: 1px;
    }
}
</style>
